extends Node
class_name Inventory

signal inventory_changed()
signal item_added(item_id: String, count: int)
signal item_removed(item_id: String, count: int)

var items := []
var max_slots := 20

func _ready():
	# 初始化空背包
	for i in range(max_slots):
		items.append({"id": "", "count": 0})

func add_item(item_id: String, count: int) -> bool:
	if count <= 0:
		return false
	
	# 先尝试堆叠到现有物品
	for item in items:
		if item.id == item_id:
			item.count += count
			item_added.emit(item_id, count)
			inventory_changed.emit()
			return true
	
	# 找空槽位
	for item in items:
		if item.id == "" or item.count == 0:
			item.id = item_id
			item.count = count
			item_added.emit(item_id, count)
			inventory_changed.emit()
			return true
	
	# 背包满了
	return false

func remove_item(item_id: String, count: int) -> bool:
	if count <= 0:
		return false
	
	var total_count = get_item_count(item_id)
	if total_count < count:
		return false
	
	var remaining = count
	for item in items:
		if item.id == item_id and remaining > 0:
			var remove_count = min(item.count, remaining)
			item.count -= remove_count
			remaining -= remove_count
			
			if item.count <= 0:
				item.id = ""
				item.count = 0
	
	item_removed.emit(item_id, count)
	inventory_changed.emit()
	return true

func get_item_count(item_id: String) -> int:
	var total = 0
	for item in items:
		if item.id == item_id:
			total += item.count
	return total

func has_item(item_id: String, count: int = 1) -> bool:
	return get_item_count(item_id) >= count

func get_items() -> Array:
	return items.duplicate()

func load_from_data(inventory_data: Array):
	items.clear()
	
	# 加载保存的物品
	for item_data in inventory_data:
		items.append({
			"id": item_data.get("id", ""),
			"count": item_data.get("count", 0)
		})
	
	# 补齐空槽位
	while items.size() < max_slots:
		items.append({"id": "", "count": 0})
	
	inventory_changed.emit()

func get_save_data() -> Array:
	var save_data := []
	for item in items:
		if item.id != "" and item.count > 0:
			save_data.append({
				"id": item.id,
				"count": item.count
			})
	return save_data

func clear():
	for item in items:
		item.id = ""
		item.count = 0
	inventory_changed.emit()

func get_item_name(item_id: String) -> String:
	match item_id:
		"seed_turnip":
			return "萝卜种子"
		"seed_potato":
			return "土豆种子"
		"seed_corn":
			return "玉米种子"
		"turnip":
			return "萝卜"
		"potato":
			return "土豆"
		"corn":
			return "玉米"
		_:
			return "未知物品"